package com.ai.zhly.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import com.ai.dmc.index.base.impl.base.BaseServiceImpl;
import com.ai.dmc.index.base.impl.jotmBase.BaseMServiceImpl;
import com.ai.dmc.index.base.sequence.SequenceGenerator;
import com.ai.dmc.index.common.InitParam;
import com.ai.dmc.index.common.bean.AnalysisBean;
import com.ai.dmc.index.common.bean.AreaBean;
import com.ai.dmc.index.common.bean.CommonBaseBean;
import com.ai.dmc.index.common.bean.FuncBean;
import com.ai.dmc.index.common.bean.JobBean;
import com.ai.dmc.index.common.bean.LinkBean;
//import com.ai.dmc.index.common.bean.StaffSessBean;
import com.ai.dmc.index.common.bean.UserBean;
import com.ai.dmc.index.common.cache.AreaCache;
import com.ai.dmc.index.common.exception.BusinessException;
import com.ai.dmc.index.common.util.BasicKMeans;
import com.ai.dmc.index.common.util.DateUtil;
import com.ai.dmc.utils.json.JsonUtil;
import com.ai.frame.bean.InputObject;
import com.ai.frame.bean.OutputObject;
import com.ai.frame.logger.Logger;
import com.ai.frame.logger.LoggerFactory;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
 * 
* @Title: MapDataImpl.java
* @Description: 家装宽带展示层service
* @author xueyf3  
* @date 2016年5月23日 下午4:22:54
* Copyright：Copyright (c) 2016
* Company：北京亚信智慧数据科技有限公司
* @version V1.0
 */
public class LinkServiceImpl extends BaseServiceImpl implements ILinkService{
	// 定义对应Mapper文件的命名空间
    private static final String NAMESPACE = "Func.";
    private static final String NAMESPACE_JOB = "Job.";
    private static final String NAMESPACE_USER = "User.";
    private static final String NAMESPACE_LINK = "ManageLink.";

	//private StaffSessBean staffSessBean;
    public static Logger log = LoggerFactory.getServiceLog(LinkServiceImpl.class);

    private SequenceGenerator sequenceGenerator;
    
    private ICommonService commonService;
    
    private IJobUtilService jobUtil;
    
    private IFuncUtilService funcUtil;

    public void setSequenceGenerator(SequenceGenerator sequenceGenerator) {
        this.sequenceGenerator = sequenceGenerator;
    }
    

	public void setCommonService(ICommonService commonService) {
		this.commonService = commonService;
	}
	
	
	public void setJobUtil(IJobUtilService jobUtil) {
		this.jobUtil = jobUtil;
	}


	public void setFuncUtil(IFuncUtilService funcUtil) {
		this.funcUtil = funcUtil;
	}


	@Override
	public void queryAllTree(InputObject inputObject, OutputObject outputObject) throws BusinessException {
		//String userId=inputObject.getParams().get("userId");
		String areaId=inputObject.getParams().get("areaId");
		String isAdmin_s=inputObject.getParams().get("isAdmin");
		boolean isAdmin=false;
		if(isAdmin_s.equals("true")){
			isAdmin= true;
		}
		//inputObject.getParams().put("userId", userId);
		//inputObject.getParams().put("areaId", areaId);
		//inputObject.getParams().put("isAdmin", isAdmin_s);
		//查询功能列表
		List<FuncBean> ffList = null;
		List<FuncBean> fList = null;
		List<FuncBean> ufList = null;
		JSONArray jArr = new JSONArray();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		ffList = this.getBaseDao().queryForList(
                NAMESPACE + "queryFuncFolderList", inputObject.getParams(),FuncBean.class);
		fList = this.getBaseDao().queryForList(
                NAMESPACE + "queryFuncList", inputObject.getParams(),FuncBean.class);
		ufList = this.getBaseDao().queryForList(
                NAMESPACE + "queryFuncListByUserId", inputObject.getParams(),FuncBean.class);
		
		// 数据判空
				if (null == ffList) {
					ffList = new ArrayList<FuncBean>();
				}
				if (null == fList) {
					fList = new ArrayList<FuncBean>();
				}
				if (null == ufList) {
					ufList = new ArrayList<FuncBean>();
				}

				// 权限过滤1-根据功能状态过滤
				if (!isAdmin) {
					Iterator<FuncBean> it_f = fList.iterator();
					while (it_f.hasNext()) {
						FuncBean f = it_f.next();
						String status = f.getStatus();

						// 不启动的功能对非admin的管理员屏蔽
						if ("0".equals(status)) {
							it_f.remove();
						}
					}
				}

				// 权限过滤2-根据用户的功能权限
				if (!isAdmin) {
					// 转成map，避免嵌套循环
					Map<String, String> ufMap = new HashMap<String, String>();
					for (FuncBean f : ufList) {
						if (null != f) {
							ufMap.put(f.getFuncId(), "");
						}
					}

					Iterator<FuncBean> it_f2 = fList.iterator();
					while (it_f2.hasNext()) {
						FuncBean f = it_f2.next();
						String fId = f.getFuncId();

						// 不启动的功能对非admin的管理员屏蔽
						if (!ufMap.containsKey(fId)) {
							it_f2.remove();
						}
					}
				}

				// 功能树根节点
				JSONObject root = new JSONObject();
				root.put("id", "ROOT");
				root.put("name", "根节点");
				root.put("isParent", true);
				root.put("nocheck", true);
				jArr.add(root);

				// 数据处理--功能文件夹
				if (ffList != null && ffList.size() > 0) {
					for (FuncBean f : ffList) {
						String fId = f.getFuncId();
						String fName = f.getFuncName();
						String parentId = f.getParentFuncId();
						String status = f.getStatus() == null ? "" : f.getStatus();
						JSONObject j = new JSONObject();

						if (null == parentId || parentId.length() == 0) {
							parentId = "ROOT";
						}

						j.put("id", fId);
						j.put("name", fName);
						j.put("pId", parentId);
						j.put("status", status);
						j.put("isParent", true);
						jArr.add(j);
					}
				}

				// 数据处理--功能
				if (fList != null && fList.size() > 0) {
					for (FuncBean f : fList) {
						String fId = f.getFuncId();
						String fName = f.getFuncName();
						String parentId = f.getParentFuncId();
						String status = f.getStatus() == null ? "" : f.getStatus();
						JSONObject j = new JSONObject();

						if (null == parentId || parentId.length() == 0) {
							parentId = "ROOT";
						}

						j.put("id", fId);
						j.put("name", fName);
						j.put("pId", parentId);
						j.put("status", status);
						j.put("type", "func");
						jArr.add(j);
					}
				}
				 resultMap.put("func", null == jArr ? "" : jArr);
		//查询角色树
				 JSONArray jobArr = new JSONArray();
				 List<JobBean> jList = null;
				 jList=this.getBaseDao().queryForList(
						 NAMESPACE_JOB + "queryJobList", inputObject.getParams(),JobBean.class);
				// 判空
					if (null == jList) {
						jList = new ArrayList<JobBean>();
					}

					// 权限过滤
					if (!isAdmin) {
						Iterator<JobBean> it_j = jList.iterator();
						while (it_j.hasNext()) {
							JobBean j = it_j.next();
							if (!jobUtil.validateUserJobRight(j, areaId)) {
								it_j.remove();
							}
						}
					}

					// 地市全量信息
					Map<String, AreaBean> allMap = (Map<String, AreaBean>) AreaCache.areaCache
							.get(AreaBean.TYPE_ALL);

					// 添加归属地市
					Iterator<JobBean> it_j2 = jList.iterator();
					while (it_j2.hasNext()) {
						JobBean j = it_j2.next();
						String jaId = j.getAreaId();
						AreaBean ab = allMap.get(jaId);
						if (null != ab) {
							j.setAreaName(ab.getAreaName());
						}
					}

					//return jList;
					// 查询地市数据
					Map<String, AreaBean> cityMap = AreaCache.areaCache
							.get(AreaBean.TYPE_CITY);
					Map<String, AreaBean> countyMap = AreaCache.areaCache
							.get(AreaBean.TYPE_COUNTY);

					// 根节点
					JSONObject j = new JSONObject();
					j.put("id", InitParam.DEPLOY_PROVINCE_ID);
					j.put("name", InitParam.DEPLOY_PROVINCE_NAME);
					j.put("pId", "");
					j.put("nocheck", true);
					jobArr.add(j);

					// 树节点排重
					Set<String> treeOnly = new HashSet<String>();

					// job树
					for (JobBean jb : jList) {
						String jId = jb.getJobId();
						String jName = jb.getJobName();
						String jaId = jb.getAreaId();
						j = new JSONObject();
						j.put("id", jId);
						j.put("name", jName);
						j.put("pId", jaId);
						j.put("type", "job");
						if (!treeOnly.contains(jId)) {
							jobArr.add(j);
							treeOnly.add(jId);
						}

						// 地市
						if (cityMap.containsKey(jaId)) {
							AreaBean ab = cityMap.get(jaId);
							String aId = ab.getAreaId();
							String aName = ab.getAreaName();
							String aUpperId = InitParam.DEPLOY_PROVINCE_ID;
							j = new JSONObject();
							j.put("id", aId);
							j.put("name", aName);
							j.put("pId", aUpperId);
							j.put("nocheck", true);
							if (!treeOnly.contains(aId)) {
								jobArr.add(j);
								treeOnly.add(aId);
							}
						}

						// 区县
						if (countyMap.containsKey(jaId)) {
							AreaBean ab = countyMap.get(jaId);
							String aId = ab.getAreaId();
							String aName = ab.getAreaName();
							String aUpperId = ab.getUpperId();
							j = new JSONObject();
							j.put("id", aId);
							j.put("name", aName);
							j.put("pId", aUpperId);
							j.put("nocheck", true);
							if (!treeOnly.contains(aId)) {
								jobArr.add(j);
								treeOnly.add(aId);

								// 区县的上一级地市也需要添加
								ab = cityMap.get(aUpperId);
								aId = ab.getAreaId();
								aName = ab.getAreaName();
								aUpperId = InitParam.DEPLOY_PROVINCE_ID;
								j = new JSONObject();
								j.put("id", aId);
								j.put("name", aName);
								j.put("pId", aUpperId);
								j.put("nocheck", true);
								if (!treeOnly.contains(aId)) {
									jobArr.add(j);
									treeOnly.add(aId);
								}
							}

						}
		resultMap.put("job", null == jobArr ? "" : jobArr);
		
		//查询用户树
		JSONArray uArr = new JSONArray();
		List<UserBean> uList = null;
		uList=this.getBaseDao().queryForList(
				 NAMESPACE_USER + "queryUserList", inputObject.getParams(),UserBean.class);
		// 判空
				if (null == uList) {
					uList = new ArrayList<UserBean>();
				}

				// 权限过滤
				if (!isAdmin) {
					Iterator<UserBean> it_u = uList.iterator();
					while (it_u.hasNext()) {
						UserBean u = it_u.next();
						if (validateUserUserRight(u, areaId)) {
							it_u.remove();
						}
					}
				}

				// 地市信息
				Map<String, AreaBean> u_cityMap = AreaCache.areaCache
						.get(AreaBean.TYPE_CITY);
				Map<String, AreaBean> u_countyMap = AreaCache.areaCache
						.get(AreaBean.TYPE_COUNTY);
				Map<String, AreaBean> regionMap = AreaCache.areaCache
						.get(AreaBean.TYPE_REGION);

				// 树节点排重
				Set<String> u_treeOnly = new HashSet<String>();
				// 树空节点排除
				Set<String> treeNotEmpty = new HashSet<String>();

				// 用户
				for (UserBean u : uList) {
					JSONObject u_j = new JSONObject();
					String id = u.getUserId();
					String name = u.getUserName();
					String u_areaId = u.getAreaId();
					String status = u.getStatus() == null ? "" : u.getStatus();

					u_j.put("id", id);
					u_j.put("name", name);
					u_j.put("pId", u_areaId);
					u_j.put("type", "user");
					if (!u_treeOnly.contains(id)) {
						uArr.add(u_j);
						u_treeOnly.add(id);
						treeNotEmpty.add(u_areaId);
					}
				}

				// 省
				JSONObject jp = new JSONObject();
				jp.put("id", InitParam.DEPLOY_PROVINCE_ID);
				jp.put("name", InitParam.DEPLOY_PROVINCE_NAME);
				jp.put("pId", "");
				jp.put("nocheck", true);
				uArr.add(jp);

				// 地市
				for (AreaBean ab : u_cityMap.values()) {
					JSONObject u_j = new JSONObject();
					String id = ab.getAreaId();
					String name = ab.getAreaName();
					String upper_id = InitParam.DEPLOY_PROVINCE_ID;

					u_j.put("id", id);
					u_j.put("name", name);
					u_j.put("pId", upper_id);
					u_j.put("nocheck", true);
					if (!u_treeOnly.contains(id) && treeNotEmpty.contains(id)) {
						uArr.add(u_j);
						u_treeOnly.add(id);
					}
				}

				// 区县
				for (AreaBean ab : u_countyMap.values()) {
					JSONObject u_j = new JSONObject();
					String id = ab.getAreaId();
					String name = ab.getAreaName();
					String upper_id = ab.getUpperId();

					u_j.put("id", id);
					u_j.put("name", name);
					u_j.put("pId", upper_id);
					if (!u_treeOnly.contains(id) && treeNotEmpty.contains(id)) {
						uArr.add(u_j);
						u_treeOnly.add(id);

						// 地市也需要添加
						AreaBean cb = u_cityMap.get(upper_id);
						String cid = cb.getAreaId();
						String cname = cb.getAreaName();
						String cupper_id = InitParam.DEPLOY_PROVINCE_ID;

						u_j.put("id", cid);
						u_j.put("name", cname);
						u_j.put("pId", cupper_id);
						u_j.put("nocheck", true);
						if (!u_treeOnly.contains(cid)) {
							uArr.add(u_j);
							u_treeOnly.add(cid);
						}
					}
				}

				// 景区
				for (AreaBean ab : regionMap.values()) {
					JSONObject u_j = new JSONObject();
					String id = ab.getAreaId();
					String name = ab.getAreaName();
					String upper_id = ab.getUpperId();

					u_j.put("id", id);
					u_j.put("name", name);
					u_j.put("pId", upper_id);
					u_j.put("nocheck", true);
					if (!u_treeOnly.contains(id) && treeNotEmpty.contains(id)) {
						uArr.add(u_j);
						u_treeOnly.add(id);

						// 地市也需要添加
						AreaBean cb = u_cityMap.get(upper_id);
						String cid = cb.getAreaId();
						String cname = cb.getAreaName();
						String cupper_id = InitParam.DEPLOY_PROVINCE_ID;

						u_j.put("id", cid);
						u_j.put("name", cname);
						u_j.put("pId", cupper_id);
						u_j.put("nocheck", true);
						if (!u_treeOnly.contains(cid)) {
							uArr.add(u_j);
							u_treeOnly.add(cid);
						}
					}
				}
			resultMap.put("user", null == uArr ? "" : uArr);

	        outputObject.setObject(JsonUtil.Object2Json(resultMap));		
		}	
	}
	
	@Override
	public void applyQueryJobFuncByUser(InputObject inputObject, OutputObject outputObject) throws BusinessException {
		String userId=inputObject.getParams().get("selUserId");

		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<LinkBean> jl= new ArrayList<LinkBean>();
		List<LinkBean> fl= new ArrayList<LinkBean>();

		if (null == userId) {
			return;
		}

		// 查询数据-根据用户查询角色
		List<LinkBean> lList = this.getBaseDao().queryForList(
	                NAMESPACE_LINK + "jobUserQueryList", inputObject.getParams(),LinkBean.class);
		

		// 数据处理-根据用户查询角色
		if (lList != null && lList.size() > 0) {
			for (LinkBean b : lList) {
				if (userId.equals(b.getUserId())) {
					jl.add(b);
				}
			}
		}
		JSONArray jArr = new JSONArray();
		for (LinkBean b : jl) {
			jArr.add(b.getJobId());
		}
		resultMap.put("job", null == jArr ? "" : jArr);
		
		
		
		// 查询数据-根据用户查询功能
			List<LinkBean> fList = this.getBaseDao().queryForList(
		                NAMESPACE_LINK + "userFuncQueryList", inputObject.getParams(),LinkBean.class);
			
		// 数据处理-根据用户查询功能
		if (fList != null && fList.size() > 0) {
			for (LinkBean b : fList) {
				if (userId.equals(b.getUserId())) {
					fl.add(b);
				}
			}
		}
		JSONArray fArr = new JSONArray();				
		for (LinkBean b : fl) {
			fArr.add(b.getFuncId());
		}
		resultMap.put("func", null == fArr ? "" : fArr);
        outputObject.setObject(JsonUtil.Object2Json(resultMap));
	}
	@Override
	public void applyQueryUserFuncByJob(InputObject inputObject, OutputObject outputObject) throws BusinessException {
		String jobId=inputObject.getParams().get("jobId");

		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<LinkBean> ul= new ArrayList<LinkBean>();
		List<LinkBean> fl= new ArrayList<LinkBean>();

		if (null == jobId) {
			return;
		}

		// 查询数据-根据角色查询用户		
		List<LinkBean> uList =this.getBaseDao().queryForList(
                NAMESPACE_LINK + "jobUserQueryList", inputObject.getParams(),LinkBean.class);
		// 数据处理
		if (uList != null && uList.size() > 0) {
			for (LinkBean b : uList) {
				if (jobId.equals(b.getJobId())) {
					ul.add(b);
				}
			}
		}
		JSONArray uArr = new JSONArray();
		for (LinkBean b : ul) {
			uArr.add(b.getUserId());
		}
		resultMap.put("user", null == uArr ? "" : uArr);
		
		// 查询数据-根据角色查询功能		
		List<LinkBean> fList =this.getBaseDao().queryForList(
                NAMESPACE_LINK + "jobFuncQueryList", inputObject.getParams(),LinkBean.class);
		// 数据处理
		if (fList != null && fList.size() > 0) {
			for (LinkBean b : fList) {
				if (jobId.equals(b.getJobId())) {
					fl.add(b);
				}
			}
		}
		JSONArray fArr = new JSONArray();
		for (LinkBean b : fl) {
			fArr.add(b.getFuncId());
		}
		resultMap.put("func", null == fArr ? "" : fArr);

        outputObject.setObject(JsonUtil.Object2Json(resultMap));
				
	}
	
	@Override
	public void applyQueryUserJobByFunc(InputObject inputObject, OutputObject outputObject) throws BusinessException {
		String funcId=inputObject.getParams().get("funcId");

		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<LinkBean> ul= new ArrayList<LinkBean>();
		List<LinkBean> jl= new ArrayList<LinkBean>();

		if (null == funcId) {
			return;
		}
		// 查询数据-根据功能查询用户
		List<LinkBean> uList =this.getBaseDao().queryForList(
                NAMESPACE_LINK + "userFuncQueryList", inputObject.getParams(),LinkBean.class);
		// 数据处理
		if (uList != null && uList.size() > 0) {
			for (LinkBean b : uList) {
				if (funcId.equals(b.getFuncId())) {
					ul.add(b);
				}
			}
		}
		JSONArray uArr = new JSONArray();
		for (LinkBean b : ul) {
			uArr.add(b.getUserId());
		}
		resultMap.put("user", null == uArr ? "" : uArr);
		
		// 查询数据-根据功能查询角色
		List<LinkBean> jList =this.getBaseDao().queryForList(
                NAMESPACE_LINK + "jobFuncQueryList", inputObject.getParams(),LinkBean.class);
		// 数据处理
		if (jList != null && jList.size() > 0) {
			for (LinkBean b : jList) {
				if (funcId.equals(b.getFuncId())) {
					jl.add(b);
				}
			}
		}
		JSONArray jArr = new JSONArray();
		for (LinkBean b : jl) {
			jArr.add(b.getJobId());
		}
		resultMap.put("job", null == jArr ? "" : jArr);

        outputObject.setObject(JsonUtil.Object2Json(resultMap));
	}
	
	@Override
	public void applyModify(InputObject inputObject, OutputObject outputObject) throws BusinessException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		String users = inputObject.getParams().get("users");
		String jobs = inputObject.getParams().get("jobs");
		String funcs = inputObject.getParams().get("funcs");
		
		List<String> userIds = null;
		List<String> jobIds = null;
		List<String> funcIds = null;

		if (null != users && users.length() > 0) {
			String[] u = users.split(";");
			userIds = Arrays.asList(u);
		} else {
			userIds = new ArrayList<String>();
		}
		if (null != jobs && jobs.length() > 0) {
			String[] j = jobs.split(";");
			jobIds = Arrays.asList(j);
		} else {
			jobIds = new ArrayList<String>();
		}
		if (null != funcs && funcs.length() > 0) {
			String[] f = funcs.split(";");
			funcIds = Arrays.asList(f);
		} else {
			funcIds = new ArrayList<String>();
		}
//		staffSessBean = SessionInfoUtil.getStaffSessBean(getRequest().getHttpRequest().getSession());
//		Boolean flag = linkModule.applyModify(userIds, jobIds, funcIds,
//				staffSessBean);
		Boolean flag = true;
		if (userIds.size() > 0 && jobIds.size() > 0 && funcIds.size() > 0) {
			// 保存user和job，job和func，不保存user和func
			flag = applyModifyUserJob(userIds, jobIds,inputObject);
			flag = applyModifyJobFunc(jobIds, funcIds,inputObject);
		} else if (userIds.size() > 0 && jobIds.size() > 0
				&& funcIds.size() == 0) {
			// 保存user和job
			flag = applyModifyUserJob(userIds, jobIds,inputObject);
		} else if (userIds.size() > 0 && jobIds.size() == 0
				&& funcIds.size() > 0) {
			// 保存user和func
			flag = applyModifyUserFunc(userIds, funcIds,inputObject);
		} else if (userIds.size() == 0 && jobIds.size() > 0
				&& funcIds.size() > 0) {
			// 保存job和func
			flag = applyModifyJobFunc(jobIds, funcIds,inputObject);
		}

		resultMap.put("result", null == flag ? "" : flag);

        outputObject.setObject(JsonUtil.Object2Json(resultMap));
	
	}
	
	
	
	@Override
	public void applyDelete(InputObject inputObject, OutputObject outputObject) throws BusinessException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		String users = inputObject.getParams().get("users");
		String jobs = inputObject.getParams().get("jobs");
		String funcs = inputObject.getParams().get("funcs");
		
		List<String> userIds = null;
		List<String> jobIds = null;
		List<String> funcIds = null;

		if (null != users && users.length() > 0) {
			String[] u = users.split(";");
			userIds = Arrays.asList(u);
		} else {
			userIds = new ArrayList<String>();
		}
		if (null != jobs && jobs.length() > 0) {
			String[] j = jobs.split(";");
			jobIds = Arrays.asList(j);
		} else {
			jobIds = new ArrayList<String>();
		}
		if (null != funcs && funcs.length() > 0) {
			String[] f = funcs.split(";");
			funcIds = Arrays.asList(f);
		} else {
			funcIds = new ArrayList<String>();
		}
//		Boolean flag = linkModule.applyDelete(userIds, jobIds, funcIds,
//				staffSessBean);
//		this.appendObject("result", flag);
		Boolean flag = false;

		if (userIds.size() > 0) {
			if (jobIds.size() > 0) {
				flag = applyDeleteUserJob(userIds, jobIds, inputObject);
			}

			if (funcIds.size() > 0) {
				flag = applyDeleteUserFunc(userIds, funcIds, inputObject);
			}
		} else if (jobIds.size() > 0) {
			if (funcIds.size() > 0) {
				flag = applyDeleteJobFunc(jobIds, funcIds, inputObject);
			}
		}
		
		resultMap.put("result", null == flag ? "" : flag);

        outputObject.setObject(JsonUtil.Object2Json(resultMap));
	
	}
	
	
	/**
	 * 
	 * @Description : 数据权限管理-初始化树
	 * 
	 * @return Boolean
	 * 
	 * @author : wucm
	 * @date : 2015年11月12日 下午7:58:10
	 * 
	 */
	@Override
	public void queryAllScopeTree(InputObject inputObject, OutputObject outputObject) throws BusinessException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String areaId=inputObject.getParams().get("areaId");
		String isAdmin_s=inputObject.getParams().get("isAdmin");
		boolean isAdmin=false;
		if(isAdmin_s.equals("true")){
			isAdmin= true;
		}
		//查询地市树
		JSONArray area = commonService.queryAreaTree(areaId, isAdmin);
		
		resultMap.put("area", null == area ? "" : area);		
		
		//查询用户树
				JSONArray uArr = new JSONArray();
				List<UserBean> uList = null;
				uList=this.getBaseDao().queryForList(
						 NAMESPACE_USER + "queryUserList", inputObject.getParams(),UserBean.class);
				// 判空
						if (null == uList) {
							uList = new ArrayList<UserBean>();
						}

						// 权限过滤
						if (!isAdmin) {
							Iterator<UserBean> it = uList.iterator();
							while (it.hasNext()) {
								UserBean u = it.next();
								if (validateUserUserRight(u, areaId)) {
									it.remove();
								}
							}
						}

						// 地市信息
						Map<String, AreaBean> u_cityMap = AreaCache.areaCache
								.get(AreaBean.TYPE_CITY);
						Map<String, AreaBean> u_countyMap = AreaCache.areaCache
								.get(AreaBean.TYPE_COUNTY);
						Map<String, AreaBean> regionMap = AreaCache.areaCache
								.get(AreaBean.TYPE_REGION);

						// 树节点排重
						Set<String> u_treeOnly = new HashSet<String>();
						// 树空节点排除
						Set<String> treeNotEmpty = new HashSet<String>();

						// 用户
						for (UserBean u : uList) {
							JSONObject u_j = new JSONObject();
							String id = u.getUserId();
							String name = u.getUserName();
							String u_areaId = u.getAreaId();
							String status = u.getStatus() == null ? "" : u.getStatus();

							u_j.put("id", id);
							u_j.put("name", name);
							u_j.put("pId", u_areaId);
							u_j.put("type", "user");
							if (!u_treeOnly.contains(id)) {
								uArr.add(u_j);
								u_treeOnly.add(id);
								treeNotEmpty.add(u_areaId);
							}
						}

						// 省
						JSONObject jp = new JSONObject();
						jp.put("id", InitParam.DEPLOY_PROVINCE_ID);
						jp.put("name", InitParam.DEPLOY_PROVINCE_NAME);
						jp.put("pId", "");
						jp.put("nocheck", true);
						uArr.add(jp);

						// 地市
						for (AreaBean ab : u_cityMap.values()) {
							JSONObject u_j = new JSONObject();
							String id = ab.getAreaId();
							String name = ab.getAreaName();
							String upper_id = InitParam.DEPLOY_PROVINCE_ID;

							u_j.put("id", id);
							u_j.put("name", name);
							u_j.put("pId", upper_id);
							u_j.put("nocheck", true);
							if (!u_treeOnly.contains(id) && treeNotEmpty.contains(id)) {
								uArr.add(u_j);
								u_treeOnly.add(id);
							}
						}

						// 区县
						for (AreaBean ab : u_countyMap.values()) {
							JSONObject u_j = new JSONObject();
							String id = ab.getAreaId();
							String name = ab.getAreaName();
							String upper_id = ab.getUpperId();

							u_j.put("id", id);
							u_j.put("name", name);
							u_j.put("pId", upper_id);
							if (!u_treeOnly.contains(id) && treeNotEmpty.contains(id)) {
								uArr.add(u_j);
								u_treeOnly.add(id);

								// 地市也需要添加
								AreaBean cb = u_cityMap.get(upper_id);
								String cid = cb.getAreaId();
								String cname = cb.getAreaName();
								String cupper_id = InitParam.DEPLOY_PROVINCE_ID;

								u_j.put("id", cid);
								u_j.put("name", cname);
								u_j.put("pId", cupper_id);
								u_j.put("nocheck", true);
								if (!u_treeOnly.contains(cid)) {
									uArr.add(u_j);
									u_treeOnly.add(cid);
								}
							}
						}

						// 景区
						for (AreaBean ab : regionMap.values()) {
							JSONObject u_j = new JSONObject();
							String id = ab.getAreaId();
							String name = ab.getAreaName();
							String upper_id = ab.getUpperId();

							u_j.put("id", id);
							u_j.put("name", name);
							u_j.put("pId", upper_id);
							u_j.put("nocheck", true);
							if (!u_treeOnly.contains(id) && treeNotEmpty.contains(id)) {
								uArr.add(u_j);
								u_treeOnly.add(id);

								// 地市也需要添加
								AreaBean cb = u_cityMap.get(upper_id);
								String cid = cb.getAreaId();
								String cname = cb.getAreaName();
								String cupper_id = InitParam.DEPLOY_PROVINCE_ID;

								u_j.put("id", cid);
								u_j.put("name", cname);
								u_j.put("pId", cupper_id);
								u_j.put("nocheck", true);
								if (!u_treeOnly.contains(cid)) {
									uArr.add(u_j);
									u_treeOnly.add(cid);
								}
							}
						}
					resultMap.put("user", null == uArr ? "" : uArr);

			        outputObject.setObject(JsonUtil.Object2Json(resultMap));
	}
	
	@Override
	public void scopeQueryAreaByUser(InputObject inputObject, OutputObject outputObject) throws BusinessException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String userId=inputObject.getParams().get("selUserId");
		JSONArray jArr = new JSONArray();
		if (null == userId) {
			return;
		}		
		List<LinkBean> list = new ArrayList<LinkBean>();
		// 查询数据		
		List<LinkBean> lList = null;		
			lList = this.getBaseDao().queryForList(
					 NAMESPACE_USER + "scopeQueryList", inputObject.getParams(),LinkBean.class);
			
		// 数据处理
		if (lList != null && lList.size() > 0) {
			for (LinkBean b : lList) {
				if (userId.equals(b.getUserId())) {
					list.add(b);
				}
			}
		}
		
		for (LinkBean b : list) {
			jArr.add(b.getAreaId());
		}
		
		resultMap.put("result", null == jArr ? "" : jArr);

        outputObject.setObject(JsonUtil.Object2Json(resultMap));
	}
	
	@Override
	public void scopeQueryUserByArea(InputObject inputObject, OutputObject outputObject) throws BusinessException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String areaId=inputObject.getParams().get("selAreaId");
		
		JSONArray jArr = new JSONArray();

		//List<LinkBean> list = linkModule.scopeQueryUserByArea(areaId);
		
		List<LinkBean> list = new ArrayList<LinkBean>();

		if (null == areaId) {
			return;
		}

		// 查询数据
		List<LinkBean> lList = null;
		
		lList = this.getBaseDao().queryForList(
				 NAMESPACE_USER + "scopeQueryList", inputObject.getParams(),LinkBean.class);

		// 数据处理
		if (lList != null && lList.size() > 0) {
			for (LinkBean b : lList) {
				if (areaId.equals(b.getAreaId())) {
					list.add(b);
				}
			}
		}
		for (LinkBean b : list) {
			jArr.add(b.getUserId());
		}

		resultMap.put("result", null == jArr ? "" : jArr);

        outputObject.setObject(JsonUtil.Object2Json(resultMap));
		
	}
	
	@Override
	public void scopeModify(InputObject inputObject, OutputObject outputObject) throws BusinessException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String users=inputObject.getParams().get("users");
		String areas=inputObject.getParams().get("areas");
		String adminId=inputObject.getParams().get("userId");
		String adminName=inputObject.getParams().get("userId");
		String adminTime = DateUtil.getInstance().getToday("yyyyMMddHHmmss");
		Boolean flag = true;
		int flag_del = 0;
		int flag_in = 0;
		List<String> userIds = null;
		List<String> areaIds = null;

		if (null != users && null != areas) {
			String[] u = users.split(";");
			String[] a = areas.split(";");
			userIds = Arrays.asList(u);
			areaIds = Arrays.asList(a);
		}

		//Boolean flag = linkModule.scopeModify(userIds, areaIds, staffSessBean);
		//this.appendObject("result", flag);

		if (userIds == null || userIds.size() == 0 || areaIds == null
				|| areaIds.size() == 0) {
			return;
		}

			// 只新增新的数据权限，不删除已有的数据权限
			for (String userId : userIds) {
				for (String areaId : areaIds) {
//					LinkBean param = new LinkBean();
//					param.setUserId(userId);
//					param.setAreaId(areaId);
//					param.setAdminId(session.getUserId());
//					param.setAdminName(session.getUserName());
//					param.setAdminTime(adminTime);
					Map<String,String> map = new HashMap<String, String>();
					map.put("userId", userId);
					map.put("areaId", areaId);
					map.put("adminId", adminId);
					map.put("adminName", adminName);
					map.put("adminTime", adminTime);
					// 防止插入重复数据
					//db.scopeDeleteByUserAndArea(param);
					flag_del = this.getBaseDao().delete(NAMESPACE_LINK + "scopeDeleteByUserAndArea" , map);
					
					// 插入新的数据权限
					//db.scopeInsert(param);
					flag_in = this.getBaseDao().insert(NAMESPACE_LINK + "scopeInsert", map);
				}
			}
			if(flag_del>0 || flag_in>0){
				flag=true;
			}
			resultMap.put("result", null == flag ? "" : flag);

	        outputObject.setObject(JsonUtil.Object2Json(resultMap));
		
	}
	
	@Override
	public void scopeDelete(InputObject inputObject, OutputObject outputObject) throws BusinessException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String users=inputObject.getParams().get("users");
		String areas=inputObject.getParams().get("areas");
		Boolean flag = true;
		int flag_del=0;
		List<String> userIds = null;
		List<String> areaIds = null;

		if (null != users) {
			String[] u = users.split(";");
			userIds = Arrays.asList(u);
		}

		if (null != areas) {
			String[] a = areas.split(";");
			areaIds = Arrays.asList(a);
		}

//		Boolean flag = linkModule.scopeDelete(userIds, areaIds, staffSessBean);
//		this.appendObject("result", flag);

		if (userIds == null || userIds.size() == 0) {
			return;
		}
		if (areaIds == null || areaIds.size() == 0) {
			return;
		}
		for (String userId : userIds) {
			for (String areaId : areaIds) {
	//					LinkBean b = new LinkBean();
	//					b.setUserId(userId);
	//					b.setAreaId(areaId);
	//					db.scopeDeleteByUserAndArea(b);
				Map<String,String> map = new HashMap<String, String>();
				map.put("userId", userId);
				map.put("areaId", areaId);
				// 防止插入重复数据
				//db.scopeDeleteByUserAndArea(param);
				flag_del = this.getBaseDao().delete(NAMESPACE_LINK + "scopeDeleteByUserAndArea" , map);
				
				
			}
		}
		if(flag_del>0){
			flag=true;
		}
		resultMap.put("result", null == flag ? "" : flag);

        outputObject.setObject(JsonUtil.Object2Json(resultMap));
	
	}
	

	
	
	/**
	 * 
	 * @Description : 应用权限管理-用户和角色
	 * @param userIds
	 * @param jobIds
	 * @param session
	 * @return
	 * @return Boolean
	 * 
	 * @author : wucm
	 * @date : 2015年8月18日 下午4:59:11
	 * 
	 */
	public Boolean applyModifyUserJob(List<String> userIds, List<String> jobIds ,InputObject inputObject) {
		Boolean flag = true;
		int flag_del=0;
		int flag_in=0;
		String adminTime = DateUtil.getInstance().getToday("yyyyMMddHHmmss");
		String adminId=inputObject.getParams().get("userId");
		String adminName=inputObject.getParams().get("userId");
			if (userIds != null && userIds.size() > 0) {
				// 多个用户，只新增新的角色，不删除已有的角色
				for (String userId : userIds) {
					for (String jobId : jobIds) {
//						LinkBean param = new LinkBean();
//						param.setUserId(userId);
//						param.setJobId(jobId);
//						param.setAdminId(session.getUserId());
//						param.setAdminName(session.getUserName());
//						param.setAdminTime(adminTime);

						Map<String,String> map = new HashMap<String, String>();
							map.put("userId", userId);
							map.put("jobId", jobId);
							map.put("adminId", adminId);
							map.put("adminName", adminName);
							map.put("adminTime", adminTime);
						// 防止插入重复数据
						//jobUserDeleteByUserAndJob(param);
						flag_del = this.getBaseDao().delete(NAMESPACE_LINK + "jobUserDeleteByUserAndJob" , map);
								
						// 插入新的角色
						//jobUserInsert(param);
						flag_in = this.getBaseDao().insert(NAMESPACE_LINK + "jobUserInsert", map);
					}
				}
			}
			if(flag_del>0 || flag_in>0){
				flag=true;
			}
		return flag;
	}
	/**
	 * 
	 * @Description : 应用权限管理-角色和功能
	 * @param jobIds
	 * @param funcIds
	 * @param session
	 * @return
	 * @return Boolean
	 * 
	 * @author : wucm
	 * @date : 2015年8月18日 下午4:59:11
	 * 
	 */
	public Boolean applyModifyJobFunc(List<String> jobIds, List<String> funcIds ,InputObject inputObject) {
		Boolean flag = true;
		int flag_del=0;
		int flag_in=0;
		String adminTime = DateUtil.getInstance().getToday("yyyyMMddHHmmss");
		String adminId=inputObject.getParams().get("userId");
		String adminName=inputObject.getParams().get("userId");

			if (jobIds != null && jobIds.size() > 0) {
				// 多个用户，只新增新的功能，不删除已有的功能
				for (String jobId : jobIds) {
					for (String funcId : funcIds) {
//						LinkBean param = new LinkBean();
//						param.setJobId(jobId);
//						param.setFuncId(funcId);
//						param.setAdminId(session.getUserId());
//						param.setAdminName(session.getUserName());
//						param.setAdminTime(adminTime);
						Map<String,String> map = new HashMap<String, String>();
							map.put("jobId", jobId);
							map.put("funcId", funcId);
							map.put("adminId", adminId);
							map.put("adminName", adminName);
							map.put("adminTime", adminTime);
						// 防止插入重复数据
						//db.jobFuncDeleteByFuncAndJob(param);
						flag_del = this.getBaseDao().delete(NAMESPACE_LINK + "jobFuncDeleteByFuncAndJob" , map);
									
						// 插入新的功能
						//db.jobFuncInsert(param);
						flag_in = this.getBaseDao().insert(NAMESPACE_LINK + "jobFuncInsert", map);
													
					}
				}
			}
			if(flag_del>0 || flag_in>0){
				flag=true;
			}
		return flag;
	}
	
	/**
	 * 
	 * @Description : 应用权限管理-用户和功能
	 * @param userIds
	 * @param funcIds
	 * @param session
	 * @return
	 * @return Boolean
	 * 
	 * @author : wucm
	 * @date : 2015年8月18日 下午4:59:11
	 * 
	 */
	public Boolean applyModifyUserFunc(List<String> userIds,
			List<String> funcIds ,InputObject inputObject) {
		Boolean flag = true;
		int flag_del=0;
		int flag_in=0;

		String adminTime = DateUtil.getInstance().getToday("yyyyMMddHHmmss");
		String adminId=inputObject.getParams().get("userId");
		String adminName=inputObject.getParams().get("userId");
		
			if (userIds != null && userIds.size() > 0) {
				// 多个用户，只新增新的功能，不删除已有的功能
				for (String userId : userIds) {
					for (String funcId : funcIds) {
//						LinkBean param = new LinkBean();
//						param.setUserId(userId);
//						param.setFuncId(funcId);
//						param.setAdminId(session.getUserId());
//						param.setAdminName(session.getUserName());
//						param.setAdminTime(adminTime);
						Map<String,String> map = new HashMap<String, String>();
						map.put("userId", userId);
						map.put("funcId", funcId);
						map.put("adminId", adminId);
						map.put("adminName", adminName);
						map.put("adminTime", adminTime);
						// 防止插入重复数据
						//db.userFuncDeleteByFuncAndUser(param);
						flag_del = this.getBaseDao().delete(NAMESPACE_LINK + "userFuncDeleteByFuncAndUser" , map);
												
						// 插入新的功能
						//db.userFuncInsert(param);
						flag_in = this.getBaseDao().insert(NAMESPACE_LINK + "userFuncInsert", map);
												
					}
				}
			}
			if(flag_del>0 || flag_in>0){
				flag=true;
			}		
		return flag;
	}
	
	/**
	 * 
	 * @Description :根据用户和角色编码，一一对应删除
	 * @author xueyf3
	 * @date 创建时间：2015年9月6日 下午4:41:51
	 * @version 1.0
	 */
	private Boolean applyDeleteUserJob(List<String> userIds,
			List<String> jobIds, InputObject inputObject) {
		Boolean flag = true;
		int flag_del=0;
		String adminTime = DateUtil.getInstance().getToday("yyyyMMddHHmmss");
		String adminId=inputObject.getParams().get("userId");
		String adminName=inputObject.getParams().get("userId");
		// 多个用户，只新增新的角色，不删除已有的角色
			for (String userId : userIds) {
				for (String jobId : jobIds) {
//					LinkBean param = new LinkBean();
//					param.setUserId(userId);
//					param.setJobId(jobId);
//					param.setAdminId(staffSessBean.getUserId());
//					param.setAdminName(staffSessBean.getUserName());
//					param.setAdminTime(adminTime);
					Map<String,String> map = new HashMap<String, String>();
					map.put("userId", userId);
					map.put("jobId", jobId);
					map.put("adminId", adminId);
					map.put("adminName", adminName);
					map.put("adminTime", adminTime);
					// 防止插入重复数据
					//db.jobUserDeleteByUserAndJob(param);
					flag_del = this.getBaseDao().delete(NAMESPACE_LINK + "jobUserDeleteByUserAndJob" , map);
					
				}
			}
			if(flag_del>0){
				flag=true;
			}
			
		return flag;
	}
	/**
	 * 
	 * @Description :根据用户和功能编码，一一对应删除
	 * @author xueyf3
	 * @date 创建时间：2015年9月6日 下午4:41:51
	 * @version 1.0
	 */
	private Boolean applyDeleteUserFunc(List<String> userIds,
			List<String> funcIds, InputObject inputObject) {
		Boolean flag = true;
		int flag_del=0;
		String adminTime = DateUtil.getInstance().getToday("yyyyMMddHHmmss");
		String adminId=inputObject.getParams().get("userId");
		String adminName=inputObject.getParams().get("userId");
		// 多个用户，只新增新的角色，不删除已有的角色
			for (String userId : userIds) {
				for (String funcId : funcIds) {
//					LinkBean param = new LinkBean();
//					param.setUserId(userId);
//					param.setFuncId(funcId);
//					param.setAdminId(staffSessBean.getUserId());
//					param.setAdminName(staffSessBean.getUserName());
//					param.setAdminTime(adminTime);
					Map<String,String> map = new HashMap<String, String>();
					map.put("userId", userId);
					map.put("funcId", funcId);
					map.put("adminId", adminId);
					map.put("adminName", adminName);
					map.put("adminTime", adminTime);
					// 防止插入重复数据
					//db.userFuncDeleteByFuncAndUser(param);
					flag_del = this.getBaseDao().delete(NAMESPACE_LINK + "userFuncDeleteByFuncAndUser" , map);
					
				}
			}
			if(flag_del>0){
				flag=true;
			}
		return flag;
	}
	
	/**
	 * 
	 * @Description :根据角色和功能编码，一一对应删除
	 * @author xueyf3
	 * @date 创建时间：2015年9月6日 下午4:41:51
	 * @version 1.0
	 */
	private Boolean applyDeleteJobFunc(List<String> jobIds,
			List<String> funcIds,InputObject inputObject) {
		Boolean flag = true;
		int flag_del=0;
		String adminTime = DateUtil.getInstance().getToday("yyyyMMddHHmmss");
		String adminId=inputObject.getParams().get("userId");
		String adminName=inputObject.getParams().get("userId");
		// 多个用户，只新增新的角色，不删除已有的角色
			for (String jobId : jobIds) {
				for (String funcId : funcIds) {
//					LinkBean param = new LinkBean();
//					param.setJobId(jobId);
//					param.setFuncId(funcId);
//					param.setAdminId(staffSessBean.getUserId());
//					param.setAdminName(staffSessBean.getUserName());
//					param.setAdminTime(adminTime);

					Map<String,String> map = new HashMap<String, String>();
					map.put("jobId", jobId);
					map.put("funcId", funcId);
					map.put("adminId", adminId);
					map.put("adminName", adminName);
					map.put("adminTime", adminTime);
					// 防止插入重复数据
					//db.jobFuncDeleteByFuncAndJob(param);
					flag_del = this.getBaseDao().delete(NAMESPACE_LINK + "jobFuncDeleteByFuncAndJob" , map);
					
				}
			}
			if(flag_del>0){
				flag=true;
			}
		return flag;
	}

	/**
	 * 
	 * @Description : 验证用户是否可以管理某个用户，根据用户的归属地
	 * 
	 * @return Boolean
	 * 
	 * @author : wucm
	 * @date : 2015年11月12日 下午7:58:10
	 * 
	 */
	public static Boolean validateUserUserRight(UserBean userBean,
			String userAreaId) {
		String areaId = userBean.getAreaId();

		if (InitParam.DEPLOY_PROVINCE_ID.equals(userAreaId)) {
			// 省级用户
			return true;
		} else {
			// 非省级用户
			// 非本地市的角色不能管理
			if (!areaId.contains(userAreaId)) {
				return false;
			}
		}

		return true;
	}
}
